package com.aldobucchi.x.flash.geom
{
	import flash.display.DisplayObject;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	public class PointUtil
	{
		
		
		public static const ORIGIN:Point = new Point( 0, 0 );

		
		/**
		 * 
		 * Local to Global to Local. 
		 * Useful for mapping points from one coordinate space to another
		 * 
		 * @param point
		 * @param localCoordinateSpace
		 * @param targetCoordinateSpace
		 * @return 
		 * 
		 */
		public static function lgl( point:Point, localCoordinateSpace:DisplayObject, targetCoordinateSpace:DisplayObject ):Point
		{
			point = localCoordinateSpace.localToGlobal( point );
			point = targetCoordinateSpace.globalToLocal( point );
			return point;		
		}
		
		
		
		
		
		public static function getSurroundingPoints( point	:Point,	radius:uint=1 ):Array
		{
			var 	x:int, 
					y:int, 
					tx:int = point.x + radius ,
					ty:int = point.y + radius ,
					points:Array = [];
					
			for ( x=point.x-radius; x<=tx; x++ )
				for ( y=point.y-radius; y<=ty; y++ )
					if ( ( point.x != x ) && ( point.y != y ) )
						points.push( new Point( x, y ) );
			
			return points;
		}
		
		
		
		
		/**
		 * 
		 * Returns the smallest rectangle that contains all the points
		 * 
		 * @param points
		 * @return 
		 * 
		 */		
		public static function getBoundingRect( points:Array ):Rectangle
		{
			
			var l:int = points.length;
			
			if ( l == 0 )
				return null;
			
			var sx:Array = points.sortOn( "x", Array.NUMERIC | Array.RETURNINDEXEDARRAY );
			var sy:Array = points.sortOn( "y", Array.NUMERIC | Array.RETURNINDEXEDARRAY );

			l--;
			
			var x0:int = points[sx[0]].x;
			var x1:int = points[sx[l]].x;
			
			var y0:int = points[sy[0]].y;
			var y1:int = points[sy[l]].y;				

			return new Rectangle( 
					x0, 
					y0, 
					x1 - x0,
					y1 - y0
					);
			
		}
		
		

	}

}